package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosRelationDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalDcPublicConsts;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public abstract class KitePosBaseRelationHandler {

    @Autowired
    private IInfServiceBus infServiceBus;

    protected String genInstanceId(String userInstanceId, List<KitePosRelationDTO> oldRelations) {
        // 订单修改、重提等，实例ID需要用订单中心返回的
        oldRelations = Optional.ofNullable(oldRelations).orElse(Lists.newArrayList()).stream()
            .filter(rela -> KiteStringUtils.equals(userInstanceId, rela.getUserInstId())).collect(Collectors.toList());
        if (!KiteListUtils.isEmpty(oldRelations)) {
            return oldRelations.get(0).getInstanceId();
        }
        return SeqUtils.getNext("SEQ_USER_ID");
    }

    protected List<Map<String, Object>> queryRelation(String sceneInstId, String relationKind) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String offerInstId = Optional.ofNullable(sceneInst).map(KiteSceneInst::getRootInstId).orElse("");
        String custId = Optional.ofNullable(sceneInst).map(KiteSceneInst::getCustId).orElse("");
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, offerInstId);
        String offerCategoryId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getCateId)
            .orElse("");

        String relationkind = DcPublicCache.getCodea(LocalDcPublicConsts.DC_20210426002, offerCategoryId);
        if (!KiteStringUtils.isEmpty(relationkind)) {
            relationKind = relationkind;
        }

        return infServiceBus.queryRelationRoles(offerCategoryId, relationKind);
    }
}
